<?php


namespace App\Service\OpenShop\Feishu;


use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\OpenShopCacheEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Library\Rms\RmsShopApi;
use App\Models\BaseModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Kuafu\Qiyuesuo\bean\Template;

class MainProcessService extends BaseService
{
    /**
     * 生成orderNo
     * @param string $prefix
     * @return string
     */
    public static function generateOrderNo(string $prefix = "KD"): string
    {
        return vsprintf("%s%s%s", [
            $prefix,
            date("Ymd", time()),
            str_pad(
                floor(microtime(true) * 1000) - strtotime(date('Y-m-d 00:00:00'), time()) * 1000,
                8,
                "0",
                STR_PAD_LEFT
            )
        ]);
    }

    /**
     * 通过orderNo获取pid
     * @param string $orderNo
     * @return int
     */
    public static function getPidByOrderNo(string $orderNo): int
    {
        return Cache::remember(OpenShopCacheEnum::getPidByOrderNo($orderNo), 86400, function () use ($orderNo) {
            return (int)OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->value('pid');
        });
    }


    public static function getIsPidOrder($orderNo)
    {
        $orderInfo = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->first();
        if ($orderInfo['childOrder'] == OpenShopMainProcessModel::CHILD_TYPE_MAIN) {
            return ['isMain' => true, 'mainOrderNo' => ''];
        } else {
            //查询主订单号
            $mainOrderNo = OpenShopMainProcessModel::query()->where('id', $orderInfo['pid'])->value('orderNo');
            return ['isMain' => false, 'mainOrderNo' => $mainOrderNo];
        }
    }

    /**
     * 获取订单的阶段数量
     * @param int $stepStatus
     * @return int
     */
    public static function countByStepStatus(array $orderPermission, int $stepStatus): int
    {
        return OpenShopMainProcessModel::query()
                                       ->join('open_shop_sign_order as order', 'order.mainProcessId',
                                           'open_shop_main_process.id')
                                       ->when(!$orderPermission['isAll'], function ($query) use ($orderPermission) {
                                           $query->whereRaw("open_shop_main_process." . $orderPermission['rawSql']);
                                       })
                                       ->where('nowStepStatus', $stepStatus)
                                       ->where('order.status', '>', SignOrderEnum::ORDER_STATUS_NO)
                                       ->count();
    }

    /**
     * 各阶段的订单数统计
     * @param array $orderPermissionList
     * @return array|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function stepCount(array $orderPermissionList)
    {
        $lists = OpenShopMainProcessModel::query()
                                         ->join('open_shop_sign_order as order', 'order.mainProcessId', '=',
                                             'open_shop_main_process.id')
                                         ->where('order.status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                                         ->when(!$orderPermissionList['isAll'],
                                             function ($query) use ($orderPermissionList) {
                                                 $query->whereRaw("open_shop_main_process." . $orderPermissionList['rawSql']);
                                             })
                                         ->select("nowStepStatus", DB::raw("count(*) as ct"))
                                         ->groupBy('nowStepStatus')
                                         ->get()
                                         ->keyBy('nowStepStatus')
                                         ->toArray();

        $lists[MissionTemplateEnum::STEP_STATUS_100] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_100,
            'ct'            => OpenShopUserContractModel::getRefundDecorationDepositOrderCount($orderPermissionList['rawSql']),
        ];

        $lists[MissionTemplateEnum::STEP_STATUS_101] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_101,
            'ct'            => OpenShopSignOrderModel::countDisclosure($orderPermissionList),
        ];

        $lists[MissionTemplateEnum::STEP_STATUS_102] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_102,
            'ct'            => OpenShopSignOrderModel::countDel($orderPermissionList),
        ];

        $lists[MissionTemplateEnum::STEP_STATUS_103] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_103,
            'ct'            => OpenShopSignOrderModel::countCancelOrder($orderPermissionList),
        ];

        $lists[MissionTemplateEnum::STEP_STATUS_104] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_104,
            'ct'            => OpenShopSignOrderModel::countCloseOrder($orderPermissionList),
        ];

        //已营业
        $lists[MissionTemplateEnum::STEP_STATUS_999] = [
            'nowStepStatus' => MissionTemplateEnum::STEP_STATUS_999,
            'ct'            => OpenShopSignOrderModel::query()->where('status', SignOrderEnum::ORDER_STATUS_COMPLETE)
                                                     ->count(),
        ];

        //统计全部
        $lists['total'] = [
            'nowStepStatus' => 0,
            'ct'            => OpenShopSignOrderModel::query()->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)
                                                     ->count(),
        ];

        return $lists;
    }

    public static function getMainByShopIds(array $shopIds): array
    {
        $query = OpenShopMainProcessModel::query()
                                         ->whereIn('shopId', $shopIds)
                                         ->select('id', 'shopId', 'nowStepStatus', 'childLocationOrder')
                                         ->orderByDesc('id')
                                         ->limit(99999);

        $sql = BaseModel::toSqlWithParam($query);

        return DB::select("select * from ({$sql}) a group by shopId");
    }

    /**
     * 通过shopIds获取加盟商信息
     * @param array $shopIds
     * @return Collection
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getMerchantNameByShopIds(array $shopIds, ?Collection $shopInfos = null): Collection
    {
        if (!$shopInfos) {
            $shopInfos = collect((new RmsShopApi())->getShopByIds($shopIds,
                    ['id', 'shopCode', 'name'])['data']['shopList'] ?? [])->keyBy('id');
        }

        $shopCodes       = $shopInfos->pluck('shopCode');
        $merchantUserIds = OpenShopSignOrderModel::query()
                                                 ->with('progressRel')
                                                 ->whereIn('shopCode', $shopCodes)
                                                 ->orderByDesc('id')
                                                 ->select('shopCode', 'merchantUserId', 'mainProcessId')
                                                 ->get()
                                                 ->map(function ($item) {
                                                     return [
                                                         'shopId'         => $item->progressRel->shopId ?? 0,
                                                         'merchantUserId' => $item->merchantUserId,
                                                     ];
                                                 })->keyBy('shopId');

        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($merchantUserIds->pluck('merchantUserId')
                                                                                     ->toArray())['data'])->keyBy('id');

        return collect($shopIds)->map(function ($shopId) use ($merchantUserIds, $userInfos) {
            return [
                'shopId' => $shopId,
                'userId' => $merchantUserId = $merchantUserIds[$shopId]['merchantUserId'] ?? 0,
                'name'   => $userInfos[$merchantUserId]['username'] ?? '',
            ];
        })->keyBy('shopId');
    }

    /**
     * 获取门店开店状态在确认建店之后的门店
     * @return array
     */
    public static function getShopsByStepStatus(): array
    {
        return OpenShopMainProcessModel::query()
            ->where('nowStepStatus', '>', MissionTemplateEnum::STEP_STATUS_6)// 建店信息待确认
            ->where('shopId', '>', 0)
            ->groupBy('shopId')
            ->get()
            ->pluck('shopId')
            ->toArray();
    }
}
